/**
 * @fileOverview
 * @name server.js
 * @author qzl
 * @license
 */
var color = require('colors');
var jspserver = require('./lib/fmk-jsp');
var n_path = require('path');
var fs = require('fs');
var R = require('ramda');
var u = require('./util/util.js');

function readJson(path) {
    var readFile = function(path) {
        return JSON.parse(fs.readFileSync(path, 'utf-8'));
    };
    var path = n_path.join(process.cwd(), path);
    return R.ifElse(fs.existsSync, readFile, function() {
        console.log(R.concat(path, "文件找不到").red);
        process.exit(-1);
    })(path);
}

function readHomeJson(path) {
    var readFile = function(path) {
        return JSON.parse(fs.readFileSync(path, 'utf-8'));
    };
    var path = n_path.join(u.home, path);
    return R.ifElse(fs.existsSync, readFile,R.always({}))(path);
}
var homeconfig = readHomeJson('g-cart-server.json');
var config = readJson('./g-cart-server.json');
config = R.merge(config, homeconfig);
var cmd = jspserver.start(config.jettry.root, config.jettry.port);
var jettryout = (function(flag) {
    return function(data) {
        var msg = data.toString();
        if (msg.indexOf("Welcome To The JFinal World") != -1) {
            flag = true;
            msg = "gome-jsp-fremark 已经启动 root:" + config.jettry.root;
        }

        if (flag) console.log(msg.green);
    };
}(false));
var express = require('express');
var app = express();
var all = function(a, b) {
    app.all(a, b);
};
var http = require('http').createServer(app);
var gmroute = require('./lib/gmroute.js');
var groute = function(routes, app) {
    var doroute = R.ifElse(R.is(String),
        R.pipe(readJson, R.partialRight(groute, [app])),
        function(route) {
            console.log(route.toString().rainbow.bold);
            app.all(R.head(route),
                gmroute(R.tail(route), config));
        });
    R.forEach(doroute, routes);
};
var pipe = require('./lib/pipe.js');
var dirtostatic = function(path) {
    app.use(express.static(path));
};

all('/', pipe(config.statics));
//静态文件映射
R.map(dirtostatic, config.statics);

//jsp服务器信息打印
cmd.stdout.on('data', jettryout);
cmd.on('close', function() {
    console.log("gome-jsp-fremark 停止运行".red);
});
groute(config.project.routes, app);
http.listen(config.node.port, function() {
    console.log(("node服务已启动端口是 " + config.node.port).cyan);
});



// ftl to fn 工程
require('./lib/watchtpl')(config);
require('./lib/watchsprite')(config);
